<template>
    <div class="book" style="flex: 1;padding: 10px;">
        <!-- 功能区域 -->
        <div style="padding: 10px 0">
            <el-button type="primary" @click="add">新增</el-button>
            <el-button type="primary">导入</el-button>
            <el-button type="primary">导出</el-button>
        </div>
        <!-- 搜索区域 -->
        <div style="margin: 10px 0; ">
            <el-input v-model="search" placeholder="请输入关键字" style="width: 20%;" clearable></el-input>
            <el-button type="primary" style="margin-left:  10px;" @click="load">查询</el-button>
        </div>
        <el-table :data="tableData" border stripe style="width: 100%">
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="bookName" label="书名" />
            <el-table-column prop="price" sortable label="价格" />
            <el-table-column prop="author" sortable label="作者" />
            <el-table-column prop="createTime" sortable label="出版时间" />
            <el-table-column prop="cover" label="封面">
                <template #default="scope">
                    <el-image ref="upload" style="width: 100px; height: 100px" :src="scope.row.cover" :zoom-rate="1.2"
                        :max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.cover]" :initial-index="4"
                        fit="cover" />
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="Operations">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleClick(scope.row)">编辑</el-button>
                    <el-popconfirm title="确认删除吗?" @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button type="danger" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px auto;">
            <el-pagination style="margin: 0 auto;" v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" v-if="total" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />

            <el-dialog v-model="dialogVisible" title="提示" width="30%">
                <el-form :model="form" label-width="auto" style="max-width: 600px">
                    <el-form-item label="书名">
                        <el-input v-model="form.bookName" />
                    </el-form-item>
                    <el-form-item label="价格">
                        <el-input v-model="form.price" />
                    </el-form-item>
                    <el-form-item label="作者">
                        <el-input v-model="form.author" />
                    </el-form-item>
                    <el-form-item label="出版时间">
                        <el-date-picker v-model="form.createTime" type="date" placeholder="Pick a day"
                            value-format="YYYY-MM-DD" :disabled-date="disabledDate" :shortcuts="shortcuts" :size="size" />
                    </el-form-item>
                    <el-form-item label="封面">
                        <el-upload ref="uploadRef" action="/api/files/upload" :file-list="fileList"
                            :on-success="fileUploadSuccess" limit=" 1" :on-exceed="handleExceed">
                            <el-button type="primary">点击上传</el-button>
                            <!-- <template #tip>
                                <div class="el-upload__tip text-red">
                                    限制一个文件，新的文件将覆盖旧的文件
                                </div>
                            </template> -->
                        </el-upload>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="save" :plain="true">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>
<script setup lang="ts" name="Book">
import { nextTick, onBeforeMount, onMounted, reactive, ref } from 'vue';
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { genFileId } from 'element-plus'
import { ElMessage } from 'element-plus'
import request from '../utils/request';



let form = ref({
    id: '',
    bookName: '',
    price: '',
    author: '',
    createTime: '',
    cover: ''
})
const dialogVisible = ref(false)
const search = ref()
const total = ref()
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const disabled = ref(false)
const background = ref(false)
let tableData = ref([])
const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
}
let fileList = reactive([])
const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
const shortcuts = [
    {
        text: '今天',
        value: new Date(),
    },
    {
        text: '昨天',
        value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date
        },
    },
    {
        text: '一周前',
        value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            return date
        },
    },
]
const size = ref<'default' | 'large' | 'small'>('default')

const handleSizeChange = (pageSize: number) => {
    pageSize = pageSize
    load()
}
const handleCurrentChange = (pageNUM: number) => {
    currentPage.value = pageNUM
    load()
}

const uploadRef = ref();

function handleClick(row: any) {
    dialogVisible.value = true
    form.value = JSON.parse(JSON.stringify(row))
    if(uploadRef.value) {
        uploadRef.value.clearFiles();
    }
}

function handleDelete(id: any) {
    // console.log(id);
    request.delete('/book/' + id).then(res => {
        if (res.code === '0') {
            ElMessage({
                message: '删除成功',
                type: 'success'
            })
        }
        else {
            ElMessage({
                message: res.msg,
                type: 'error'
            })
        }
        load()
    })
}


onBeforeMount(() => {
    load()
})

function fileUploadSuccess(res: any) {
    load()
    form.value.cover = res.data
}



function load() {
    request.get('/book', {
        params: {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            search: search.value
        }
    }).then(res => {
        tableData.value = res.data.records
        total.value = res.data.total
        currentPage.value = res.data.current
        pageSize.value = res.data.size
    })
}

const add = () => {
    dialogVisible.value = true,
    form.value = {
            id: '',
            bookName: '',
            price: '',
            author: '',
            createTime: '',
            cover: ''
    }
     //console.log(upload.value);
    // 当需要清除文件时，调用这个方法
    nextTick(()=>{
        if(uploadRef.value) {
        uploadRef.value.clearFiles();
    }
    })
}

function save() {
    if (form.value.id) {
        request.put('/book', form.value).then(res => {
            // console.log(res);
            if (res.code === '0') {
                ElMessage({
                    message: '修改成功',
                    type: 'success'
                })
            }
            else {
                ElMessage({
                    message: res.msg,
                    type: 'error'
                })
            }
            dialogVisible.value = false
            load()
        })
    }
    else {
        request.post('/book', form.value).then(res => {
            console.log(res);
            dialogVisible.value = false
            ElMessage({
                // title:'提示',
                message: '新增成功',
                type: 'success'
            })
            load()
        })
    }

}

</script>

<style scoped></style>
